package se.ramfelt.psn.web.us;

import java.io.IOException;
import java.net.MalformedURLException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.client.ClientProtocolException;
import org.json.JSONException;

import se.ramfelt.psn.model.Friend;
import se.ramfelt.psn.web.BadRequestResponseException;
import se.ramfelt.psn.web.ForbiddenResponseException;
import se.ramfelt.psn.web.FriendListRetrievalException;
import se.ramfelt.psn.web.UnauthorizedResponseException;
import se.ramfelt.psn.web.UnexpectedResponseCodeException;

public class UsPlaystationNetwork {

    private final UsPlaystationSite site;
    private final String username;
    private final String password;

    public UsPlaystationNetwork(UsPlaystationSite site, String username, String password) {
        this.site = site;
        this.username = username;
        this.password = password;
    }

    public void login() throws MalformedURLException, IOException, UnexpectedResponseCodeException, UnauthorizedResponseException, ForbiddenResponseException, BadRequestResponseException {
        if (!site.isLoggedIn()) {
            site.login(username, password);
        }
    }

    public List<Friend> getFriendList() throws ClientProtocolException, IOException, JSONException, FriendListRetrievalException, ParseException {
        // for each friend
        // get JSON
        // build friend from JSON

        ArrayList<Friend> list = new ArrayList<Friend>();
        for (String name : site.getFriendNames()) {
            list.add(getFriend(name));
        }
        return list;
    }

    public Friend getFriend(String name) throws ClientProtocolException, IOException, JSONException, ParseException {
        return new FriendFactory().createFriend(site.getFriendSummary(name));
    }
}
